//
//  ShowEmotionTool.swift
//  showEmotionDemo
//
//  Created by maker on 2016/11/24.
//  Copyright © 2016年 maker. All rights reserved.
//

import UIKit

class ShowEmotionTool: NSObject {
    static let shareIntance : ShowEmotionTool = ShowEmotionTool()
    lazy var manager : EmotionManager = EmotionManager()
    
    func getAttrStr(_ statusText:String?,font:UIFont?) -> NSMutableAttributedString? {
        
        guard let statusText = statusText else {
            return nil
        }
        
        //1.创建规则
        let parttern = "\\[.*?\\]"
        
        //2.创建正则表达式对象
        guard let regex = try? NSRegularExpression(pattern: parttern, options: []) else {
            return nil
        }
        
        //3.匹配结果
        let results = regex.matches(in: statusText, options: [], range: NSRange(location: 0, length: statusText.characters.count))
        
        //4.从结果集中截取字符串
        let mutableAttr = NSMutableAttributedString(string: statusText)
        
        for i in (0...results.count) {
            let result = results[i]
            
            let chs = (statusText as NSString).substring(with: result.range)
            
            guard let imagePath = getImagPath(chs) else {
                return nil
            }
            
            let image = UIImage(contentsOfFile: imagePath)
            let attachment = NSTextAttachment()
            attachment.image = image
            attachment.bounds = CGRect(x: 0, y: -4, width: font!.lineHeight, height: font!.lineHeight)
            let attrString = NSAttributedString(attachment: attachment)
            
            mutableAttr.replaceCharacters(in: result.range, with: attrString)

        }
        return mutableAttr
    
    }
    
    
    //获取路径
    fileprivate func getImagPath(_ chs : String) -> String? {
        
        for package in manager.packages {
            for emotion in package.emotions {
                if emotion.chs == chs {
                    return emotion.pngPath
                }
            }
        }
        return nil
    }
}
